<?php


namespace Beerus\Modules\Topic\Controllers;

use App\Admin\Extensions\WorkContent;
use App\Http\Controllers\Controller;
use App\Pockets\GridDataModel as pGridDataModel;
use Biz\service\NiceGoodsTopic\Topic;
use Doraemon\tools\Hhzurl;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Form;
use Illuminate\Http\Request;
use Illuminate\Support\MessageBag;
use Doraemon\tools\ImgUrl;
use Biz\model\NiceGoodsTopic\FirstTopic;
use Biz\model\NiceGoodsTopic\SecondTopic;
use Biz\model\NiceGoodsTopic\GoodsList;
use Doraemon\tools\IdParse;
use Doraemon\model\Blank as DbBlank;
use Doraemon\model\Member;
use Doraemon\model\Photos as DbPhotos;
use Doraemon\service\User;
use service\Wiki\Wiki;
use service\Wikiwiki\Wikiwiki;
use Biz\model\wiki\Wiki as mWiki;
use Doraemon\service\Videos\Videos;
use Encore\Admin\Widgets\Tab;

class NiceGoodsTopicController extends Controller
{
    const PAGE_SIZE = 20;

    public function __construct()
    {
        parent::__construct();
        Admin::script('$(".pjax-container").attr("id","pjax-container");');
    }

    public function index(Request $request, Content $content)
    {
        $page = $request->input('page', 1);
        $pageSize = $request->input('per_page', 20);
        $limit = [
                ($page - 1) * $pageSize,
                $pageSize

        ];
        $this->where['LIMIT'] = $limit;
        $this->where['ORDER'] = ['topic_status' => 'ASC'  , 'addtime' => 'DESC'];
        // 处理查询条件
        if ($title = $request->input('name', '')) $this->where['name[~]'] = $title;
        if ($topic_status = $request->input('topic_status', 0)) $this->where['topic_status'] = $topic_status;
        $total = (int)FirstTopic::count($this->where);
        $list = (array)FirstTopic::select('*', $this->where);
        if($list &&is_array($list)){
            foreach ($list as &$val){
                $val['status'] = ($val['topic_status'] == FirstTopic::STATUS_NORMAL) ?'已上线' :'已下线';
              $count =   SecondTopic::count(['topic_status' => SecondTopic::STATUS_NORMAL ,'pid' => $val['id']]);
              $val['topic_count'] = $count;
            }
        }
        $gridModel = new pGridDataModel($list, $total, ['perPage' => $pageSize]);
        $grid = Admin::grid($gridModel, function (Grid $grid) use ($gridModel) {
            $grid->paginate($gridModel->getPerPage());
            $grid->disableCreateButton();
            $grid->tools(function ($tool) {
                $url = "/admin/topic/goodsTopic/index/create";
                $tool->append('<a class="btn btn-warning" href="javascript:layer.open({
                                type: 2,
                                title: \'创建主题\',
                                maxmin: true,
                                shadeClose: true,
                                shade: 0,
                                area: [\'800px\', \'500px\'],
                                content: \'' . $url . '\'
                            });
               ">创建主题</a>');
                $tool->append('<a class="btn btn-warning act"  data-action="refresh">更新缓存</a>');

            });
            $grid->filter(function (Grid\Filter $filter) {
                $filter->disableIdFilter();
                $filter->column(1 / 3, function (Grid\Filter $filter) {
                    $filter->equal('name', '主题名称');
                });
                $filter->column(1 / 3, function (Grid\Filter $filter) {
                    $filter->equal('topic_status', '状态')->checkbox([
                        FirstTopic::STATUS_NORMAL=> '已上线',
                        FirstTopic::STATUS_DELETE => '已下线',
                    ]);
                });
                if ($this->where) $filter->expand();//默认展开
            });

            $grid->column('id', '主题ID');
            $grid->column('name', '主题名称')->width(150);
            $grid->column('topic_count', '专题数量');
            $grid->column('remark', '备注')->width(200);
            $grid->column('status', '上线状态')->display(function ($value, Grid\Column $column) {
                $map = [
                    '未上线' => 'primary',
                    '已上线' => 'success',
                    '已下线' => 'warning',
                ];
                return $column->label($map[$value]);
            });
            $grid->column('admin_id', '操作人')->display(function () {
                return $this->admin_id ? Admin::user()->find($this->admin_id)->name : '-';
            });
            $grid->disableExport();
            $grid->disableRowSelector();
            $grid->actions(function (Grid\Displayers\Actions $actions) {
                $actions->disableDelete();
                $actions->disableEdit();
                if ($actions->row->status == '已下线') {
                    $actions->prepend('<a class="act fa fa-arrow-up" href="javascript:;"  data-id="' . $actions->row->id . '" data-action="online">上线</a>');
                } else {
                    $actions->prepend('<a class="act fa fa-close" href="javascript:;"  data-id="' . $actions->row->id . '" data-action="offline">下线</a>');
                    $actions-> prepend("<a  class=' fa fa-edit' href='/admin/topic/secondTopic/index/{$actions->row->id}}'>二级专题</a>");

                }

                $url = "/admin/topic/goodsTopic/index/".$actions->row->id."/edit";
                $actions->append('<a class=" fa fa-edit" href="javascript:layer.open({
                                type: 2,
                                title: \'编辑\',
                                maxmin: true,
                                shadeClose: true,
                                shade: 0,
                                area: [\'800px\', \'500px\'],
                                content: \'' . $url . '\'
                            });
               ">编辑</a><br/>');
            });

        });

        Admin::script($this->indexScript());
        return $content->header("一级好物主题")->row($grid);
    }

    public function firstSave(Request $request)
    {
        $params = $request->all();

        try {
            while (true) {
                $id = $params['id'] ?? '0';
                $data = [
                    'name' => $params['name'] ?? '',
                    'remark' => $params['remark'] ?? '',
                    'admin_id' => Admin::user()->id,
                    'edittime' => date( "Y-m-d H:i:s",time()),
                ];
                if ($id > 0) {
                    FirstTopic::update($data, ['id' => $id]);
                    break;
                }
                $data['topic_status'] = FirstTopic::STATUS_NORMAL;

                $data['addtime'] = time();
               FirstTopic::insert($data);
               $id = FirstTopic::id();
                break;
            }
            $success = new MessageBag([
                'title' => '保存成功'
            ]);
                return redirect('/admin/topic/goodsTopic/index/'.$id.'/edit/?code=1')->with(compact('success'));

        } catch (\Exception $e) {
            $error = new MessageBag([
                'title' => '保存失败,' . $e->getMessage()
            ]);
            return back()->withInput()->with(compact('error'));
        }
    }

    public function firstCreate( Request $request,\App\Admin\Extensions\WorkContent $content,  $id = 0)
    {

        $code = $request->input('code', 0);
        if ($code == 1) {
            $script = <<<SCRIPT
            setTimeout(function () {
                        parent.window.location.reload();
                    }, 10);
SCRIPT;
            Admin::script($script);
        }

        if($id > 0) {
            $info = FirstTopic::getInfo($id);
        }
        $form = new Form($info);
        $form->hidden('id');
        $form->text('name', '主题名称')->required();
        $form->textarea('remark', '描述')->required();
        $form->action(route('nicegoodstopic.save'));
        $title = $id ? '修改一级主题' : '添加一级主题';
        return $content->header($title)
            ->row($form);
    }

    public function secondIndex(Request $request, Content $content ,$f_id = 0)
    {
        $params = $request->all();
        $page = $request->input('page', 1);
        $pageSize = $request->input('per_page', 20);
        $limit = [
                ($page - 1) * $pageSize,
                $pageSize
        ];
        $this->where['pid'] = $f_id;
        $this->where['LIMIT'] = $limit;
        $this->where['ORDER'] = ['show_time' => 'DESC'];
        // 处理查询条件
        if ($title = $request->input('topic_name', '')) $this->where['topic_name[~]'] = $title;
        if($params['show_time']['start'] && $params['show_time']['end']){
            $this->where['show_time[>=]'] = $params['show_time']['start'];
            $this->where['show_time[<=]'] = $params['show_time']['end'];
        }

        $total = (int)SecondTopic::count($this->where );
        $list = (array)SecondTopic::select('*', $this->where);
        $now = time();
        if($list && is_array($list)){
            foreach($list as &$val){
                    $start_at = strtotime($val['show_time']);
                    if ((int)$val['topic_status'] === SecondTopic::STATUS_NORMAL) {
                        if ($start_at <= $now) {
                            $val['status'] = SecondTopic::STATUS_END; //活动中
                        } else if ($start_at > $now) {
                            $val['status'] = SecondTopic::STATUS_WAIT; //未开始
                        }
                    }else{
                        $val['status'] = SecondTopic::STATUS_DELETE;
                    }
                    $act_status_arr = SecondTopic::STATUS_ARR;
                    $val['status_name'] = $act_status_arr[$val['status']];
                    $val['qrcode'] = \Doraemon\tools\Hhzurl::H5NiceGoodsTopic($val['id']);
                    $val['qrcode'] = json_encode([
                         'type' => 'link',
                         'link' =>\Biz\tools\helper\Common::formatFullScreenLink($val['qrcode'])]);
            }
        }
        $gridModel = new pGridDataModel($list, $total, ['perPage' => $pageSize]);
        $grid = Admin::grid($gridModel, function (Grid $grid) use ($gridModel , $f_id) {
            $grid->paginate($gridModel->getPerPage());
            $grid->filter(function (Grid\Filter $filter) {
                $filter->disableIdFilter();
                $filter->column(1 / 2, function (Grid\Filter $filter) {
                    $filter->equal('topic_name', '专题名称');
                });
                $filter->column(1 / 2, function (Grid\Filter $filter) {
                    $filter->between("show_time" , '上线时间')->datetime();
                });

                $filter->expand();//默认展开
            });
            $grid->disableCreateButton();
            $grid->tools(function ($tool) use ($f_id) {
                $url = "/admin/topic/secondTopic/index/".$f_id."/create";
                $tool->append('<a class="btn btn-warning" href="javascript:layer.open({
                                type: 2,
                                title: \'创建二级专题\',
                                maxmin: true,
                                shadeClose: true,
                                shade: 0,
                                area: [\'800px\', \'500px\'],
                                content: \'' . $url . '\'
                            });
               ">创建二级专题</a>');
            });

            $grid->column('id', '专题ID');

            $grid->column('topic_name', '专题名称');
            $grid->column('desc', '专题描述')->width(150);
            $grid->column('img', '图片')->display(function() {
                return "<img src='".ImgUrl::getUrl(ImgUrl::APPTYPE_BIZ, $this->img, ImgUrl::IMAGE_SIZE_ORI_NPHONE)."' width=100 />";
            })->width(150);
            $grid->column('qrcode', '二维码')->newQrcode();
            $grid->column('status', '状态')->using(
                SecondTopic::STATUS_ARR
                , '删除')->label([
                12 => 'success',
                9  => 'info',
                11 => 'warning',
                13 => 'danger',
            ]);

            $grid->column('show_time', '上线时间');
            $grid->column('admin_id', '操作人')->display(function () {
                return $this->admin_id ? Admin::user()->find($this->admin_id)->name : '-';
            });

            $grid->disableExport();
            $grid->disableRowSelector();

            $grid->actions(function (Grid\Displayers\Actions $actions) use ($f_id) {
                $actions->disableDelete();
                $actions->disableEdit();
                if ($actions->row->topic_status  == SecondTopic::STATUS_DELETE) {
                    $actions->prepend('<a class="act-sec fa fa-arrow-up" href="javascript:;"  data-id="' . $actions->row->id . '" data-action="online">上线</a>');
                    $actions->disableEdit();
                } else {
                    $actions->prepend('<a class="act-sec fa fa-close" href="javascript:;"  data-id="' . $actions->row->id . '" data-action="offline">下线</a>');

                }
                $actions-> prepend("<a  class=' fa fa-edit' href='/admin/topic/goodsList/index/{$actions->row->id}}'>好物编辑</a>");
                $url = "/admin/topic/secondTopic/index/".$f_id."/".$actions->row->id."/edit";
                $actions->append('<a class="fa fa-edit" href="javascript:layer.open({
                                type: 2,
                                title: \'编辑\',
                                maxmin: true,
                                shadeClose: true,
                                shade: 0,
                                area: [\'800px\', \'500px\'],
                                content: \'' . $url . '\'
                            });
               ">编辑</a>');
                $actions->append('<br/><a class="act-sec fa fa-refresh" href="javascript:;"  data-id="' . $actions->row->id . '" data-action="refresh">更新商品数</a>');

            });
        });
        Admin::script($this->indexScript());

       $info =  FirstTopic::getInfo($f_id);
        return $content->header($info['name'] .'   二级专题')->breadcrumb(
            ['text' => '一级主题列表', 'url' => '/topic/goodsTopic/index'],
            ['text' => $info['name']],

        )->row($grid);
    }

    public function secondSave(Request $request)
    {
        $params = $request->all();

        try {
            while (true) {
                $id = $params['id'] ?? '0';
                $data = [
                    'topic_name' => $params['topic_name'] ?? '',
                    'desc' => $params['desc'],
                    'img' =>$params['img'],
                    'pid' => $params['pid'],
                    'show_time' => $params['show_time'] ? :date('Y-m-d H:i:s', time()),

                    'admin_id' => Admin::user()->id,
                    'edittime' => date( "Y-m-d H:i:s",time()),
                ];
                if ($id > 0) {
                    SecondTopic::update($data, ['id' => $id]);
                    break;
                }
                $data['topic_status'] = SecondTopic::STATUS_NORMAL;

                $data['addtime'] = date( "Y-m-d H:i:s",time());
                SecondTopic::insert($data);
                $id = SecondTopic::id();
                break;
            }

            $success = new MessageBag([
                'title' => '保存成功'
            ]);
            return redirect("/admin/topic/secondTopic/index/". $params['pid']."/".$id."/edit?code=1")->with(compact('success'));
        } catch (\Exception $e) {
            $error = new MessageBag([
                'title' => '保存失败,' . $e->getMessage()
            ]);
            return back()->withInput()->with(compact('error'));
        }
    }

    public function secondCreate(Request $request ,\App\Admin\Extensions\WorkContent $content, $f_id , $id = 0)
    {
        $code = $request->input('code', 0);
        if ($code == 1) {
            $script = <<<SCRIPT
            setTimeout(function () {
                        parent.window.location.reload();
                    }, 10);
SCRIPT;
            Admin::script($script);
        }
        if($id > 0) {
            $info = SecondTopic::getInfo($id);
        }else{
            $info['pid'] = $f_id;
        }
        $form = new Form($info);
        $form->hidden('id');
        $form->hidden('pid');
        $form->text('topic_name', '专题名称')->required();
        $form->textarea('desc', '专题描述')->required();
        $form->imgUpload('img', '图片', false, ['imgType' => ImgUrl::APPTYPE_BIZ, 'imgSize' => ImgUrl::IMAGE_SIZE_ORI_PHONE_BIG]);
        $form->datetime("show_time" , '上线时间')->required("不能为空");
        $form->action(route('secondIndex.save'));
        $title = $id ? '修改二级专题' : '添加二级专题';
        return $content->header($title)
            ->row($form);
    }



    public function goodsIndex(Request $request, Content $content ,$r_id = 0)
    {
        $page = $request->input('page', 1);
        $pageSize = $request->input('per_page', 20);
        $limit = [
                ($page - 1) * $pageSize,
                $pageSize
        ];
        $this->where['rela_topic_id'] = $r_id;
        $this->where['goods_status'] = GoodsList::STATUS_NORMAL;
        $this->where['ORDER'] = [
             'sort' => 'ASC',
              'addtime' => 'DESC'
        ];
        // 处理查询条件
        if ($wiki_id = $request->input('wiki_id', '')) $this->where['wiki_id'] =  $wiki_id;
        if ($obj_id = $request->input('obj_id', '')) $this->where['obj_id'] =  $obj_id;
        $total = (int)GoodsList::count($this->where);
        $list = (array)GoodsList::select('*', $this->where);
        $noteIds = [];
        if($list && is_array($list)){
            $noteIds = array_column($list , 'obj_id');
            $wikiIds = array_column($list , 'wiki_id');
        }
        if ($noteIds) {
            $dbData = DbPhotos::getPhotos($noteIds);
            foreach ($dbData as $row) {
                $noteList[$row['id']] = $row;
            }
        }

        if($wikiIds && is_array($wikiIds)){
            $wikiInfo = mWiki::selectByWhere([
                'status[!]' => mWiki::STATUS_DELETE,
                'id' => $wikiIds,
            ]);
            if($wikiInfo && is_array($wikiInfo)){
                $wikiInfo = array_combine(array_column($wikiInfo ,'id') , $wikiInfo);
            }
        }
        $topicInfo = SecondTopic::getInfo($r_id);

        foreach ($list as &$row) {
            $row['content_desc'] = $row['content_desc'] ?  :$noteList[$row['obj_id']]['remark'];
            $row['goods_desc'] =  $row['goods_desc']  ?  :$wikiInfo[$row['wiki_id']]['title'];
            $row['topic_name'] = $topicInfo ? $topicInfo['topic_name']  : '';
            $modelList[] = $row;
        }

        $gridModel = new pGridDataModel($list, $total);
        $grid = Admin::grid($gridModel, function (Grid $grid) use ($gridModel,$r_id) {
            $grid->disablePerPageSelector();
            $grid->disablePagination();
            $grid->disableCreateButton();

            $grid->tools(function ($tool) use ($r_id) {
                $url = "/admin/topic/goodsList/index/".$r_id."/create";
                $tool->append('<a class="btn btn-warning" href="javascript:layer.open({
                                type: 2,
                                title: \'创建商品\',
                                maxmin: true,
                                shadeClose: true,
                                shade: 0,
                                area: [\'800px\', \'500px\'],
                                content: \'' . $url . '\'
                            });
               ">创建商品</a>');
            });
            $grid->filter(function (Grid\Filter $filter) {
                $filter->disableIdFilter();
                $filter->column(1 / 3, function (Grid\Filter $filter) {
                    $filter->equal('wiki_id', '商品id');
                });
                $filter->column(1 / 3, function (Grid\Filter $filter) {
                    $filter->equal('obj_id', '内容id');
                });
                if ($this->where) $filter->expand();//默认展开
            });

            $grid->column('id', '专题ID')->sort();
            $grid->column('topic_name', '专题名称');
            $grid->column('wiki_id', "商品id");
            $grid->column('goods_desc', "商品名称")->display(function ()
            {
                $html = $this->goods_desc;
                return $html;
            })->width(200);
            $grid->column('obj_id', "内容id");
            $grid->column('content_desc', "内容正文")->display(function ()
            {
                $html = $this->content_desc;
                return $html;
            })->width(200);
            $grid->column('admin_id', '操作人')->display(function () {
                return $this->admin_id ? Admin::user()->find($this->admin_id)->name : '-';
            });

            $grid->disableExport();
            $grid->disableRowSelector();

            $grid->actions(function (Grid\Displayers\Actions $actions) use($r_id) {
                $actions->disableDelete();
                $actions->disableEdit();
                $url = "/admin/topic/goodsList/index/".$r_id."/".$actions->row->id."/edit" ;
                $actions->append('<a class="fa fa-edit" href="javascript:layer.open({
                                type: 2,
                                title: \'编辑\',
                                maxmin: true,
                                shadeClose: true,
                                shade: 0,
                                area: [\'800px\', \'500px\'],
                                content: \'' . $url . '\'
                            });
               ">编辑</a>');
                $actions->prepend('<a class="act-goods fa fa-close" href="javascript:;"  data-id="' . $actions->row->id . '" data-action="offline">删除</a>');
            });

        });

        Admin::script($this->indexScript());
        return $content
            ->header($topicInfo['topic_name']." - 好物专题")
            ->breadcrumb(
                ['text' => '一级主题列表', 'url' => '/topic/goodsTopic/index'],
                ['text' => '二级主题列表', 'url' => '/topic/secondTopic/index/'.$topicInfo['pid']],
                ['text' => $topicInfo['topic_name']]

            )->row($grid);
    }

    public function goodsSave(Request $request)
    {
        $params = $request->all();

        try {
            $objType = IdParse::getType($params['obj_id']);
            $wikiInfo =  mWiki::getInfoByWikiId($params['wiki_id']);
            if(empty($wikiInfo)){
                throw new \Exception('商品不存在');
            }
            $noteInfo = DbPhotos::getPhoto($params['obj_id']);
            if(empty($noteInfo)){
                throw new \Exception('内容不存在');
            }
            while (true) {
                $id = $params['id'] ?? '0';
                $data = [
                    'rela_topic_id' => $params['rela_topic_id'] ?? '',
                    'obj_id' => $params['obj_id'] ?? '',
                    'obj_type' => $objType,
                    'wiki_id' =>  $params['wiki_id'] ?? '',
                    'goods_desc' => $params['goods_desc'] ?? "",
                    'content_desc' => $params['content_desc'] ?? "",
                    'goods_status' => GoodsList::STATUS_NORMAL,
                    'admin_id' => Admin::user()->id,
                    'edittime' => date( "Y-m-d H:i:s",time()),
                ];
                if ($id > 0) {
                    GoodsList::update($data, ['id' => $id]);
                    break;
                }
                $data['addtime'] = date( "Y-m-d H:i:s",time());
                GoodsList::insert($data);
                $id = GoodsList::id();
                break;
            }

            $success = new MessageBag([
                'title' => '保存成功'
            ]);
            Topic::setCounter($params['rela_topic_id']);
            return redirect("/admin/topic/goodsList/index/". $params['rela_topic_id']."/".$id."/edit?code=1")->with(compact('success'));
        } catch (\Exception $e) {
            $error = new MessageBag([
                'title' => '保存失败,' . $e->getMessage()
            ]);
            return back()->withInput()->with(compact('error'));
        }
    }

    public function goodsCreate(Request $request , \App\Admin\Extensions\WorkContent $content , $r_id , $id = 0)
    {

        $code = $request->input('code', 0);
        if ($code == 1) {
            $script = <<<SCRIPT
            setTimeout(function () {
                        parent.window.location.reload();
                    }, 10);
SCRIPT;
            Admin::script($script);
        }

        if($id > 0) {
            $info = GoodsList::getInfo($id);
        }else{
            $info['rela_topic_id'] = $r_id;
        }
        $form = new Form($info);
        $form->hidden('id');
        $form->hidden('rela_topic_id');
        $form->hidden('is_top');
        $form->text('wiki_id', '商品id')->required();
        $form->text('obj_id', '内容id')->required();
        $form->textarea('content_desc', '内容正文');
        $form->textarea('goods_desc', '商品名称');
        $form->action(route('goodsIndex.save'));
        $title = $id ? '修改好物' : '添加好物';
        return $content->header($title)
            ->row($form);
    }


    public function actGoods(Request $request)
    {
        $id = $request->input('id', 0);
        $act = $request->input('act', 'offline'); //top offline online
        $code = 0;
        try {
            switch ($act) {
                case 'top':
                    $msg = '置顶成功';
                    //取消其他置顶
                    $info =  GoodsList::getInfo($id);
                    GoodsList::updateByWhere(['rela_topic_id' => $info['rela_topic_id']] , ['is_top' => 0]);
                    //取消其他置顶
                    GoodsList::setTop($id);
                    break;

                case 'del-top':
                    $msg = '取消置顶成功';
                    GoodsList::delTop($id);
                    break;
                case 'offline':
                    $msg = '下线成功';
                    if (!GoodsList::isDel($id)) {
                        GoodsList::offline($id);
                    }
                    break;
                default:
                    $msg = 'nothing';
                    break;
            }

        } catch (\Exception $e) {
            $code = 1;
            $msg = $e->getMessage();
        }

        $response = [
            'code' => $code,
            'msg' => $msg,
        ];
        return response()->json($response);
    }

    public function actSec(Request $request)
    {
        $id = $request->input('id', 0);
        $act = $request->input('act', 'offline'); //top offline online
        $code = 0;
        try {
            switch ($act) {
                case 'online':
                    $msg = '上线成功';
                    if (SecondTopic::isDel($id)) {
                        //取消其他置顶
                        //取消其他置顶
                        SecondTopic::online($id);
                    }
                    break;
                case 'offline':
                    $msg = '下线成功';
                    if (!SecondTopic::isDel($id)) {
                        SecondTopic::offline($id);
                    }
                    break;
                case 'refresh':
                    $msg = '更新成功';
                     Topic::setCounter($id);
                    break;
                default:
                    $msg = 'nothing';
                    break;
            }

        } catch (\Exception $e) {
            $code = 1;
            $msg = $e->getMessage();
        }

        $response = [
            'code' => $code,
            'msg' => $msg,
        ];
        return response()->json($response);
    }



    public function act(Request $request)
    {
        $id = $request->input('id', 0);
        $act = $request->input('act', 'offline'); //top offline online
        $code = 0;
        try {
            switch ($act) {
                case 'online':
                    $msg = '上线成功';
                    if (FirstTopic::isDel($id)) {
                        //取消其他置顶
                        //取消其他置顶
                        FirstTopic::online($id);
                    }
                    break;
                case 'offline':
                    $msg = '下线成功';
                    if (!FirstTopic::isDel($id)) {
                        FirstTopic::offline($id);
                    }
                    break;
                case 'refresh':
                    $msg = '更新成功';
                    Topic::setTopicCache();
                    break;
                default:
                    $msg = 'nothing';
                    break;
            }

        } catch (\Exception $e) {
            $code = 1;
            $msg = $e->getMessage();
        }

        $response = [
            'code' => $code,
            'msg' => $msg,
        ];
        return response()->json($response);
    }

    /**
     * 前台类目排序
     * @param Request $request
     */
    public function sort(Request $request)
    {
        $sortInfo = $request->input('sort');
        if($sortInfo && is_array($sortInfo)){
            foreach($sortInfo as $key => $val){
                GoodsList::updateByWhere(['id' => $key] , ['sort' => $val]);
            }
        }
    }



    private function indexScript()
    {
        $url = route('nicegoodstopic.act');
        return <<<EOF
let close_url = '$url';
$('.act').unbind('click').click(function(){
    let id= $(this).data('id');
    let act= $(this).data('action');
    let params = {id:id, act:act};
    if (act == 'offline') {
        layer.confirm('是否下线该专题', {btn: ['是', '否']}, function (index) {
         let url = '/admin/topic/goodsTopic/index/act';
            $.post(url, params , function (rs) {
                toastr.success(rs.msg, null, {
                    timeOut : 1000
                });
                if (rs.code == 0) {
                   $.admin.reload();
                }
            });
            layer.close(layer.index);
        });
    } else if(act== 'online') {
    layer.confirm('是否上线该专题', {btn: ['是', '否']}, function (index) {
       let url = '/admin/topic/goodsTopic/index/act';
            $.post(url, params , function (rs) {
                toastr.success(rs.msg, null, {
                    timeOut : 1000
                });
                if (rs.code == 0) {
                   $.admin.reload();
                }
            });
            layer.close(layer.index);
        });
 
    }else if(act== 'refresh') {
//    layer.confirm('是否更新该专题下二级专题', {btn: ['是', '否']}, function (index) {
       let url = '/admin/topic/goodsTopic/index/act';
            $.post(url, params , function (rs) {
                toastr.success(rs.msg, null, {
                    timeOut : 1000
                });
                if (rs.code == 0) {
                   $.admin.reload();
                }
            });
//            layer.close(layer.index);
//        });
        }
});


$('.act-sec').unbind('click').click(function(){
    let id= $(this).data('id');
    let act= $(this).data('action');
    let params = {id:id, act:act};
    if (act == 'offline') {
        layer.confirm('是否下线该专题', {btn: ['是', '否']}, function (index) {
            let url = '/admin/topic/secondTopic/index/act';
            $.post(url, params , function (rs) {
                toastr.success(rs.msg, null, {
                    timeOut : 1000
                });
                if (rs.code == 0) {
                   $.admin.reload();
                }
            });
            layer.close(layer.index);
        });
    } else if(act == 'online') {
            layer.confirm('是否上线该专题', {btn: ['是', '否']}, function (index) {
            let url = '/admin/topic/secondTopic/index/act';
            $.post(url, params , function (rs) {
                toastr.success(rs.msg, null, {
                    timeOut : 1000
                });
                if (rs.code == 0) {
                   $.admin.reload();
                }
            });
            layer.close(layer.index);
        });
 
    }else if(act== 'refresh') {
    layer.confirm('是否更新该专题下商品数', {btn: ['是', '否']}, function (index) {
       let url = '/admin/topic/secondTopic/index/act';
            $.post(url, params , function (rs) {
                toastr.success(rs.msg, null, {
                    timeOut : 1000
                });
                if (rs.code == 0) {
                   $.admin.reload();
                }
            });
            layer.close(layer.index);
        });
        }
});
$('.act-goods').unbind('click').click(function(){
    let id= $(this).data('id');
    let act= $(this).data('action');
    let params = {id:id, act:act};
    if (act == 'offline') {
        layer.confirm('是否下线该商品', {btn: ['是', '否']}, function (index) {
         let url = '/admin/topic/goodsList/index/act';
            $.post(url, params , function (rs) {
                toastr.success(rs.msg, null, {
                    timeOut : 1000
                });
                if (rs.code == 0) {
                   $.admin.reload();
                }
            });
            layer.close(layer.index);
        });
    } else if(act == 'top') {
     layer.confirm('是否置顶该商品', {btn: ['是', '否']}, function (index) {
         let url = '/admin/topic/goodsList/index/act';
            $.post(url, params , function (rs) {
                toastr.success(rs.msg, null, {
                    timeOut : 1000
                });
                if (rs.code == 0) {
                   $.admin.reload();
                }
            });
            layer.close(layer.index);
        });    
    }else{
      layer.confirm('是否取消置顶商品', {btn: ['是', '否']}, function (index) {
         let url = '/admin/topic/goodsList/index/act';
            $.post(url, params , function (rs) {
                toastr.success(rs.msg, null, {
                    timeOut : 1000
                });
                if (rs.code == 0) {
                   $.admin.reload();
                }
            });
            layer.close(layer.index);
        });
    
    
    }
});
EOF;
    }
}